package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdAdminMapper;
import com.heima.admin.service.AdAdminService;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.Admin.dtos.AdLoginDto;
import com.heima.model.Admin.pojos.AdUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Liu
 * @date : 2022/1/3 0003 15:16
 */
@Service
public class AdAdminServiceImpl extends ServiceImpl<AdAdminMapper, AdUser> implements AdAdminService {
    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;

    @Value("${leadnews.jwt.expire}")
    private Integer expire;

    @Override
    public ResponseResult<Map<String, Object>> login(AdLoginDto dto) {
        if(StringUtils.isNotEmpty(dto.getName())
                && StringUtils.isNotEmpty(dto.getPassword())){

            //校验用户名和密码
            LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdUser::getName,dto.getName());
            AdUser loginUser = getOne(queryWrapper);

            if(loginUser==null){
                throw new LeadNewsException(AppHttpCodeEnum.AD_USER_DATA_NOT_EXIST);
            }

            if(!BCrypt.checkpw(dto.getPassword(),loginUser.getPassword())){
                throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //生成token给前端返回
            loginUser.setPassword(null);//在token不存储密码等敏感信息
            //loginUser.setSalt(null);
            try {
                //读取私钥文件
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
                String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);

                Map<String,Object> result = new HashMap<>();
                result.put("token",token);
                result.put("user",loginUser);
                return ResponseResult.okResult(result);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e); //系统异常
            }
        }else{
            throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
    }
}
